package com.example.mei.blueautosend;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by MEI on 2018/3/8.
 */

public class SearchUtils {
    File fileold = new File(getSDPath());
    File QQfile = new File(getSDPath() + File.separator + "Tencent"+File.separator+"QQfile_recv");
    File WeChatfile = new File(getSDPath() + File.separator + "Tencent"+File.separator+"MicroMsg");
    String keyFile = "";
    Context context;
    private int MIN_TX_INTERVAL = 100;
    String path = "";
    private String fileName;
    SearchListener listener;
    public List<String> data_list = new ArrayList<String>();
    public List<String> send_list = new ArrayList<String>();
    public List<String> address_list = new ArrayList<String>();

    public SearchUtils(Context context, SearchListener listener) {
        this.context = context;
        this.listener = listener;
    }

    public String setFile(String fileName) {
        keyFile = "";
        path = "";
        data_list.clear();
        address_list.clear();
        send_list.clear();
        if (fileName.contains(".txt") && fileName.length() > 4) {
            this.keyFile = fileName;
            BrowserFile();
            return path;
        } else {
            if (!fileName.equals("") && !fileName.contains(".")) {
                keyFile = fileName + ".txt";
                BrowserFile();
                return path;
            } else {
                Toast.makeText(context, "无效文件名", Toast.LENGTH_SHORT).show();
                return null;
            }
        }


    }

    private String getSDPath() {
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) {
            return Environment.getExternalStorageDirectory().toString();
        } else {
            return Environment.getDownloadCacheDirectory().toString();
        }
    }

    private void BrowserFile() {
        if (!keyFile.equals("")) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    search(QQfile);
                    if(path.equals("")){
                        search(WeChatfile);
                        if(path.equals("")){
                            search(fileold);
                            Looper.prepare();
                            if (path.equals("")) {
                                Toast.makeText(context, "未找到文件!", Toast.LENGTH_SHORT).show();
                            }else{
                                ReadTxtFile(path);
                                listener.onFileSearched(fileName);
                                Toast.makeText(context, "找到文件啦!", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        }else{
                            ReadTxtFile(path);
                            Looper.prepare();
                            listener.onFileSearched(fileName);
                            Toast.makeText(context, "找到文件啦!", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }else{
                        ReadTxtFile(path);
                        Looper.prepare();
                        listener.onFileSearched(fileName);
                        Toast.makeText(context, "找到文件啦!", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }




                }
            }).start();

//            search(fileold);
//
//            if (result.equals("")) {
//
//                Toast.makeText(context, "未找到文件", Toast.LENGTH_SHORT).show();
//
//            }
        }
    }

    private void search(File fileold) {
        try {
            File[] files = fileold.listFiles();
            if (files!=null&&files.length > 0) {
                for (int j = 0; j < files.length; j++) {
                    if (!files[j].isDirectory()&&files[j].getName().contains(".txt")) {
                        System.out.println("发送文件名" + files[j].getName());
                        listener.onFileSearched(files[j].getName());
                        if (files[j].getName().equalsIgnoreCase(keyFile)) {
                            System.out.println("查找到的文件" + files[j].getName());
                            path = files[j].getPath();
                            fileName = files[j].getName();
                            break;



                            //shuju.putString(files[j].getName().toString(),files[j].getPath().toString());
                        }
                    } else {
                        this.search(files[j]);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("捕获了异常"+e.getMessage());
        }


    }


    private void ReadTxtFile(String strFilePath) {
        String str = "";
        System.out.println("进了了" + strFilePath);
        //打开文件
        File file = new File(strFilePath);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory()) {
            Log.d("TestFile", "The File doesn't not exist.");
        } else {
            try {
                InputStream instream = new FileInputStream(file);
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
                //分行读取
                int byteLength = 0;
                while ((line = buffreader.readLine()) != null) {
                    byteLength += line.trim().length();
                    if (!line.trim().equals("")) {

                        if (line.contains("@")) {
                            if (address_list.size() != 0) {
                                data_list.add(str);
                                str = "";
                                address_list.add(line.replace(" ", ""));
                            } else {
                                address_list.add(line.replace(" ", ""));
                            }

                        } else if (!line.trim().equals("q")) {
                            str = str + line.replace(" ", "");

                        }

                    }
                }

                data_list.add(str);

                for (int i = 0; i < address_list.size(); i++) {
                    jinzhiCount = 1;
                    for (int j = 0; j < data_list.get(i).length() / MIN_TX_INTERVAL + 1; j++) {

//                        if (i == 0) {

                        if (MIN_TX_INTERVAL * (j + 1) > data_list.get(i).length()) {
                            if (j == 0) {
                                send_list.add(address_list.get(i) + anotherJInZhiZhuanHuan((data_list.get(i).length() - MIN_TX_INTERVAL * j) / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, data_list.get(i).length()) + getYanzheng(address_list.get(i).replace("@", "") + anotherJInZhiZhuanHuan((data_list.get(i).length() - MIN_TX_INTERVAL * j) / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, data_list.get(i).length())));
                            } else {
                                send_list.add(jinzhizhuanhuan(address_list.get(i).replace("@", ""), MIN_TX_INTERVAL / 2) + anotherJInZhiZhuanHuan((data_list.get(i).length() - MIN_TX_INTERVAL * j) / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, data_list.get(i).length()) + getYanzheng(jinzhizhuanhuan(address_list.get(i).replace("@", ""), MIN_TX_INTERVAL / 2).replace("@", "") + anotherJInZhiZhuanHuan((data_list.get(i).length() - MIN_TX_INTERVAL * j) / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, data_list.get(i).length())));
                                jinzhiCount++;
                            }
                        } else {
                            if (j == 0) {
                                send_list.add(address_list.get(i) + anotherJInZhiZhuanHuan(MIN_TX_INTERVAL / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, MIN_TX_INTERVAL * (j + 1)) + getYanzheng(address_list.get(i).replace("@", "") + anotherJInZhiZhuanHuan(MIN_TX_INTERVAL / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, MIN_TX_INTERVAL * (j + 1))));

                            } else {
                                send_list.add(jinzhizhuanhuan(address_list.get(i).replace("@", ""), MIN_TX_INTERVAL / 2) + anotherJInZhiZhuanHuan(MIN_TX_INTERVAL / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, MIN_TX_INTERVAL * (j + 1)) + getYanzheng(jinzhizhuanhuan(address_list.get(i).replace("@", ""), MIN_TX_INTERVAL / 2).replace("@", "") + anotherJInZhiZhuanHuan(MIN_TX_INTERVAL / 2) + data_list.get(i).substring(MIN_TX_INTERVAL * j, MIN_TX_INTERVAL * (j + 1))));
                                jinzhiCount++;
                            }
                        }


                    }

                }


                instream.close();

            } catch (java.io.FileNotFoundException e) {
                Log.d("TestFile", "The File doesn't not exist.");
            } catch (IOException e) {
                Log.d("TestFile", e.getMessage());
            }
        }



    }

    int jinzhiCount = 1;

    private String jinzhizhuanhuan(String date, int dateSize) {

        int a = Integer.parseInt(date, 16);
        a = a + dateSize * jinzhiCount;


        return "@" + Integer.toHexString(a).toUpperCase();
    }

    private String anotherJInZhiZhuanHuan(int dateLength) {

        String str = Integer.toHexString(dateLength).toUpperCase();
        if (str.length() == 1) {
            str = "0" + str;
        }
        return str;
    }

    private String getYanzheng(String date) {

        int charLength = 0;
        char c[] = date.toCharArray();
        for (int i = 0; i < c.length; i++) {

            charLength += (int) c[i];

        }

        String unicodeDate = "";
        if (Integer.toHexString(charLength).length() > 4) {
            unicodeDate = Integer.toHexString(charLength).substring(Integer.toHexString(charLength).length() - 4, Integer.toHexString(charLength).length());
        } else if (Integer.toHexString(charLength).length() == 3) {
            unicodeDate = "0" + Integer.toHexString(charLength);
        } else if (Integer.toHexString(charLength).length() == 2) {
            unicodeDate = "00" + Integer.toHexString(charLength);
        } else if (Integer.toHexString(charLength).length() == 4) {
            unicodeDate = Integer.toHexString(charLength);
        }

        return unicodeDate.toUpperCase();
    }


}
